using B.S.XZYData.Api.Wrter.Application.Command.Process;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Process
{
    /// <summary>
    /// 删除工序处理器
    /// </summary>
    public class DeleteProcessHandler : IRequestHandler<DeleteProcessCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Domain.ZSHH.Process> processRepo;
        private readonly IBaseRepository<ProcessCollectionData> collectionDataRepo;
        private readonly ILogger<DeleteProcessHandler> logger;

        public DeleteProcessHandler(
            IBaseRepository<Domain.ZSHH.Process> processRepo,
            IBaseRepository<ProcessCollectionData> collectionDataRepo,
            ILogger<DeleteProcessHandler> logger)
        {
            this.processRepo = processRepo;
            this.collectionDataRepo = collectionDataRepo;
            this.logger = logger;
        }

        /// <summary>
        /// 删除工序
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<int>> Handle(DeleteProcessCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

            try
            {
                // 检查工序是否存在
                var existingProcess = await processRepo.GetValue(request.Id);
                if (existingProcess == null || existingProcess.IsDeleted)
                {
                    res.Msg = "工序不存在";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                // 逻辑删除工序
                existingProcess.IsDeleted = true;
                existingProcess.Updator = request.Deleter;
                existingProcess.UpdatorDate = DateTime.Now;

                var processResult = await processRepo.UpdateAsync(existingProcess);
                if (processResult <= 0)
                {
                    res.Msg = "删除工序编号失败";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                // 逻辑删除相关的工序采集数据
                var collectionDataList = collectionDataRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.ProcessId == request.Id)
                    .ToList();

                var collectionDataResult = 0;
                foreach (var item in collectionDataList)
                {
                    item.IsDeleted = true;
                    item.Updator = request.Deleter;
                    item.UpdatorDate = DateTime.Now;
                    collectionDataResult += await collectionDataRepo.UpdateAsync(item);
                }

                res.Data = processResult + collectionDataResult;
                res.Msg = "删除工序成功";
                res.Code = ApiEnum.Success;

                logger.LogInformation($"删除工序成功，工序ID：{request.Id}，工序名称：{existingProcess.ProcessName}");

                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                logger.LogError($"删除工序异常：{ex.Message}");
                res.Msg = "删除工序异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }
    }
} 